package dao;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import utils.JDBCUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public abstract class BaseDao02 {
    QueryRunner queryRunner = new QueryRunner();

    //1.通用的增删改操作
    public int update(String sql, Object... param) {
        Connection conn = JDBCUtils.getConnection();
        try {
            return queryRunner.update(conn, sql, param);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            throw new RuntimeException(throwables);//把异常抛给Filter过滤器进行事务处理
        }
    }

    //2.查询返回一条数据
    public <T> T queryForOne(String sql,Class<T> type,Object ...param){
        Connection conn = JDBCUtils.getConnection();
        try {
            return queryRunner.query(conn,sql,new BeanHandler<T>(type),param);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            throw new RuntimeException(throwables);//把异常抛给Filter过滤器进行事务处理
        }
    }

    //3.查询返回多条数据
    public <T> List<T> queryForMore(String sql, Class<T> type, Object ...param){
        Connection conn = JDBCUtils.getConnection();
        try {
            return queryRunner.query(conn,sql,new BeanListHandler<T>(type),param);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            throw new RuntimeException(throwables);//把异常抛给Filter过滤器进行事务处理
        }
    }

    //4.查询特殊值(count(*) max(salary) ...)
    public Object queryForSpecial(String sql, Object ...param){
        Connection conn = JDBCUtils.getConnection();
        try {
            return queryRunner.query(conn,sql,new ScalarHandler(),param);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            throw new RuntimeException(throwables);//把异常抛给Filter过滤器进行事务处理
        }
    }

}
